﻿using Sustainalytics.LongRunningTaskManager;
using Sustainalytics.LongRunningTaskManager.Interface;
using Sustainalytics.OAuth.Services.Common.Client;
using System.Net.Http;
using System.Net.Http.Formatting;

namespace Sustainalytics.Portfolios.Tasks
{
    public class PortfolioSecuritiesDownloadTemplateTask : ILongRunningTask
    {
        public LongRunningTaskTypeEnum Type
        {
            get { return LongRunningTaskTypeEnum.PortfolioSecuritiesDownloadTemplate; }
        }

        public object Start(LongRunningTaskContext context)
        {
            var file = new LongRunningTaskFileInMemResult
            {
                Contents = CreateOWINController(context),
                FileName = "Portfolio Securities Template.xlsx",
                MimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            };

            return file;
        }

        private byte[] CreateOWINController(LongRunningTaskContext context)
        {
            OAuthClient oAuthClient = new OAuthClient(
                HostConfig.GetHostUrl() + HostConfig.GetSecurityResource() + "/token",
                HostConfig.GetHostUrl() + HostConfig.GetSecurityResource(),
                null,
                null);

            oAuthClient.SetAuthenticationTicket(context.Ticket);

            HttpResponseMessage resp = oAuthClient.PostAsync(null, new ObjectContent<string>(context.ParamJson, new JsonMediaTypeFormatter()),context.CancellationToken).Result;

            resp.EnsureSuccessStatusCode();

            byte[] result = resp.Content.ReadAsByteArrayAsync().Result;

            return result;
        }
    }
}
